var dtree;
layui.use(['dtree'], function () {
    dtree = layui.dtree;
});
var common = {
    joinArray: function (array, key) {
        var _itemsStr = "";
        layui.each(array, function (i, n) {
            _itemsStr += "," + n[key];
        });
        if (_itemsStr.length > 0) {
            return _itemsStr.substr(1, _itemsStr.length);
        }
        return "";
    },
    sprintf: function (str) {
        var args = arguments, flag = true, i = 1;
        str = str.replace(/%s/g, function () {
            var arg = args[i++];
            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    },
    getUrlParam: function (name) {
        if (window.location.search.indexOf('?') != -1) {
            let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            let r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
        }
    },
    currentUser: function () {
        var jsonObj = $.parseJSON(localStorage.getItem("currentUser"));
        return jsonObj;
    },
    setYearMonth: function (year, month) {
        var myDate = new Date();
        var tYear = myDate.getFullYear();
        var tMonth = myDate.getMonth();

        var m = tMonth + 1;
        if (m.toString().length == 1) {
            m = "0" + m;
        }
        $('#'+year).val(tYear);
        $('#'+month).val(m);
    }
}

var deptUtil = {
    /**
     * 初始化下拉树页面
     * @param elId 页面绑定元素Id
     * @param orgId 编辑页上面放组织机构orgId的input隐藏元素的id <input id=""/>
     * @param orgName 编辑页上面放组织机构orgName的input隐藏元素的id <input id=""/>
     */
    initDeptSelectTree: function (elId, deptId, deptName, initVal) {
        dtree.renderSelect({
            elem: "#" + elId,
            width: "350",
            url:  pName + "/system/dept/tree",
            method: 'get',
            selectInputName: {nodeId: "" + deptId, context: "" + deptName},
            skin: "layui",
            dataFormat: "list",
            response: {treeId: "id", parentId: "parentId", title: "nameAbbr"},
            selectInitVal: initVal + ""
        });
    },
    initDeptTree: function (elId, nodeClick) {
        dtree.render({
            elem: "#" + elId,
            width: '100%',
            method: "get",
            url: pName + "/system/dept/tree",
            dataFormat: "list",
            skin: "layui",
            initLevel: "2",
            response: {treeId: "id", parentId: "parentId", title: "nameAbbr"},
        });
        dtree.on("node('"+elId+"')", function (obj) {
            nodeClick(obj.param.nodeId);
        })
    },
    initUnitTree: function (elId, initVal, nodeClick, model) {
        dtree.render({
            elem: "#" + elId,
            width: '100%',
            method: "get",
            url: pName + "/system/dept/unitTree?model=" + model,
            dataFormat: "list",
            skin: "layui",
            initLevel: "2",
            response: {treeId: "id", parentId: "parentId", title: "nameAbbr"},
            selectInitVal: initVal + ""
        });
        dtree.on("node('"+elId+"')", function (obj) {
            nodeClick(obj.param.nodeId);
        })
    },
    initUnitSelect: function (elId,  deptId, deptName, initVal, nodeClick, model) {
        dtree.renderSelect({
            elem: "#" + elId,
            method: "get",
            url: pName + "/system/dept/unitTree?model=" + model,
            dataFormat: "list",
            skin: "layui",
            initLevel: "2",
            selectInputName: {nodeId: "" + deptId, context: "" + deptName},
            response: {treeId: "id", parentId: "parentId", title: "nameAbbr"},
            selectInitVal: initVal + ""
        });
        dtree.on("node('"+elId+"')", function (obj) {
            nodeClick(obj.param.nodeId);
        })
    }
}

var roleUtil = {
    initRoleSelect: function (roleId, roleName) {
        let layerIndex = layer.open({
            type: 2,
            title: '角色查询',
            shade: 0.1,
            maxmin: true,
            area: ['99%', '99%'],
            resize: true,
            content: pName + "/system/common/roleSelectMain?roleId=" + roleId + "&roleName=" + roleName
        });
        $(window).on("resize", function () {
            layer.full(layerIndex);
        });
    }
}
var userUtil = {
    initUserSelect: function (userId, userName, model) {
        let layerIndex = layer.open({
            type: 2,
            title: '人员查询',
            shade: 0.1,
            maxmin: true,
            area: ['99%', '99%'],
            resize: true,
            content: pName + "/system/common/userSelectMain?userId=" + userId + "&userName=" + userName + "&m=" + model
        });
        $(window).on("resize", function () {
            layer.full(layerIndex);
        });
    },
    initUserSelect: function (userId, userName, callback, model) {
        let layerIndex = layer.open({
            type: 2,
            title: '人员查询',
            shade: 0.1,
            maxmin: true,
            area: ['99%', '99%'],
            resize: true,
            content: pName + "/system/common/userSelectMain?userId=" + userId + "&userName=" + userName + "&m=" + model,
            end: callback
        });
        $(window).on("resize", function () {
            layer.full(layerIndex);
        });
    },
    initUserSelectMultiple: function (userId, userName, model) {
        let layerIndex = layer.open({
            type: 2,
            title: '人员多选',
            shade: 0.1,
            maxmin: true,
            area: ['99%', '99%'],
            resize: true,
            content: pName + "/system/common/userSelectMultipleMain?userId=" + userId + "&userName=" + userName+ "&m=" + model
        });
        $(window).on("resize", function () {
            layer.full(layerIndex);
        });
    }
}
var convert = {
    imageToBase64 : function (img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    }
}

var fileUtil = {
    /**
     *
     * @param fileIdEL
     * @param fileNameEL
     * @param isPre 是否回显
     */
    initFileUpload: function (fileIdEL, fileNameEL, isPre) {
        let layerIndex = layer.open({
            type: 2,
            title: '文件上传',
            shade: 0.1,
            maxmin: true,
            area: ['99%', '99%'],
            resize: true,
            content: pName + "/system/common/fileUploadMain?fileId=" + fileIdEL+ "&fileName=" + fileNameEL+ "&isPre=" + isPre
        });
        $(window).on("resize", function () {
            layer.full(layerIndex);
        });
    },
    initFilePre: function (preEL, fileIds) {
        if(fileIds != null && fileIds != ""){
            var new_element = document.createElement('link');
            new_element.setAttribute("rel", "stylesheet")
            new_element.setAttribute("href", pName + "/layuimini/lib/jq-module/zyupload/zyupload-1.0.0.min.css")
            document.body.appendChild(new_element);
            let loading = layer.load();
            $.ajax({
                url: pName + '/system/file/filesInfo?fileIds=' + fileIds,
                dataType: 'json',
                contentType: 'application/json',
                async: false,
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code == 1) {
                        let html = "";
                        let index = 0;
                        result.data.forEach(function (d) {
                            html += '<div id="uploadList_'+index+'" class="upload_append_list">\n' +
                                '     <div class="file_bar">\n' +
                                '         <div style="padding:5px;">\n' +
                                '             <p class="file_name" title="'+d.fileName+'">\n' +
                                '             '+d.fileName+'</p>\n' +
                                '             <span class="file_edit" data-index="'+index+'" title="编辑"></span>\n' +
                                '             <span class="file_del" data-index="'+index+'" title="删除" onclick="window.removeFile(d.id,"uploadList_'+index+'")"></span>\n' +
                                '         </div>\n' +
                                '     </div>\n' +
                                '     <a style="height:115px;width:140px;" href="#" class="imgBox">\n' +
                                '         <div class="uploadImg" style="width:125px;max-width:125px;max-height:105px;">\n' +
                                '             <img id="uploadImage_'+index+'"class="upload_image" src="'+pName +'/system/file/download/' +d.id+'"\n' +
                                '                 style="width:125px;">\n' +
                                '         </div>\n' +
                                '     </a>\n' +
                                '     <p id="uploadSuccess_'+index+'" class="file_success" style="display: block"></p>\n' +
                                ' </div>';
                            index++;
                        })
                        $(window.document).find("#" + preEL).append(html);

                        $(window.document).find(".upload_append_list").hover(function(e) {
                            $(window.document).find(".file_bar").addClass("file_hover")
                        }, function(e) {
                            $(window.document).find(".file_bar").removeClass("file_hover")
                        })
                        return false;
                    } else {
                        layer.alert(result.msg, {icon: 2});
                    }
                },
                error: function (err) {
                    console.log(err);
                    layer.alert("服务报错", {icon: 2});
                }
            })

        }
    }
}